package com.gs.m_login

import android.content.Intent
import android.os.Bundle
import android.view.View
import com.gs.common.BaseActivity
import com.gs.common.constant.ActionConst
import com.gs.common.util.ToastUtil
import com.gs.m_login.databinding.LoginLayoutBinding

class LoginActivity: BaseActivity(), LoginPersistent.OnDoLoginStateCallback {

    private lateinit var binding: LoginLayoutBinding
    private val loginPersistent by lazy { LoginPersistent.getInstance(this) }
    private var isUserAvailable = false
    private val areEditTextsFilled = arrayOf(false,false,false)

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        binding = LoginLayoutBinding.inflate(layoutInflater)
        setContentView(binding.root)

        //当所有编辑框被填充时，按钮被激活
        super.activeButton(
            binding.loginBtn,
            arrayOf(binding.lgUsernameOrTelnumEdt,binding.lgPasswordEdt),
            areEditTextsFilled,
            resources.getDrawable(R.drawable.login_btn_bg),
            R.color.login_btn_color,
            resources.getDrawable(R.drawable.login_btn_active_bg),
            R.color.login_btn_active_color)
    }

    fun close(view: View) {
        this.finish()
    }

    /**
     * 处理登录逻辑
     */
    fun login(view: View) {
        if (areEditTextsFilled[0]) {
            //做登录的逻辑处理
            val usernameOrPhoneNum = binding.lgUsernameOrTelnumEdt.text.toString()
            val password = binding.lgPasswordEdt.text.toString()
            //给密码加盐
            //检查用户是否存在
//        loginPersistent.checkUserState(usernameOrPhoneNum, this)
//        if (!isUserAvailable) {
//            ToastUtil.showShortToast(this, "该用户不存在")
//            return
//        }
            loginPersistent.doLogin(usernameOrPhoneNum, password, this)
        } else {
            ToastUtil.showShortToast(this, "请填写完整信息！")
        }
    }

    fun toRegister(view: View) {
        val intent = Intent().apply {
            action = ActionConst.TO_REGISTER_ACTIVITY_ACTION
        }
        startActivity(intent)
        this.finish()
    }

    override fun onLoginLoading() {
        //正在登录
        super.onLoginLoading()
    }

    override fun onLoginSuccess() {
        //登录成功
        ToastUtil.showShortToast(this, "登录成功！")
        val intent = Intent().apply {
            action = ActionConst.TO_HOME_ACTIVITY_ACTION
        }
        startActivity(intent)
        this.finish()
    }

    override fun onLoginFailed() {
        ToastUtil.showShortToast(this, "用户不存在或密码错误！")
    }

    override fun onNetworkError() {
        ToastUtil.showShortToast(this, "无法连接网络！")
    }

    override fun onServerError() {
        ToastUtil.showShortToast(this, "无法连接服务器！")
    }

    override fun onUnknownError() {
        ToastUtil.showShortToast(this, "未知错误！")
    }
}